package com.hbnu.Control;

import com.hbnu.Pojo.User;
import com.hbnu.Service.Impl.UserServiceImpl;
import com.hbnu.Service.UserService;
import com.hbnu.Util.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LogInServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String stuCode =  req.getParameter("stuCode");
        String password = req.getParameter("password");
        String remember =  req.getParameter("remember");

        User user = userService.findUserByStuCodeAdnPassword(stuCode, password);

        if (user == null) {
            req.setAttribute("error", "输入错误");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        } else {

            // 存入session
            req.getSession().setAttribute("session_user", user);

//            req.getAttribute();
            if ("remember-me".equals(remember)) {
                CookieUtils.addCookie("remember", 7 * 24 * 3600, req, resp, stuCode, password);

            }


            req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);

        }
    }
}
